package com.lk.mall.config.handler;

import com.lk.mall.common.MallException;
import com.lk.mall.config.annotation.TokenToAdminUser;
import com.lk.mall.mapper.AdminUserTokenMapper;
import com.lk.mall.model.entity.AdminUserToken;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

@Component
public class TokenToAdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private AdminUserTokenMapper adminUserTokenMapper;

    public TokenToAdminUserMethodArgumentResolver() {
    }

    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(TokenToAdminUser.class);
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {

        if (parameter.getParameterAnnotation(TokenToAdminUser.class) == null) {
            return null;
        }
        String token = webRequest.getHeader("token");
        if (null == token || "".equals(token) || token.length() != 32) {
            MallException.fail("管理员未登录！");
        }

        AdminUserToken adminUserToken = adminUserTokenMapper.selectByToken(token);
        if (adminUserToken == null) {
            MallException.fail("管理员未登录！");
        }
        if (adminUserToken.getExpireTime().getTime() <= System.currentTimeMillis()) {
            MallException.fail("管理员登录过期！请重新登录！");
        }

        return adminUserToken;
    }
}


//if (parameter.getParameterAnnotation(TokenToAdminUser.class) != null) {
//String token = webRequest.getHeader("token");
//if (null != token && !"".equals(token) && token.length() == 32) {
//    AdminUserToken adminUserToken = adminUserTokenMapper.selectByToken(token);
//    if (adminUserToken == null) {
//        MallException.fail("管理员未登录！");
//    } else if (adminUserToken.getExpireTime().getTime() <= System.currentTimeMillis()) {
//        MallException.fail("管理员登录过期！请重新登录！");
//    }
//    return adminUserToken;
//    } else {
//    MallException.fail("管理员未登录！");
//    }
//}
//return null;